package com.handler.inbound;

import com.to.FileReq;
import com.to.MetaInfo;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUploadJudgment extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        FileReq fileReq = (FileReq) msg;
        ByteBuf buf = fileReq.getFile();
        MetaInfo metaInfo = fileReq.getMetaInfo();

        Path filePath = Paths.get(metaInfo.getPath() + metaInfo.getFileName());

        boolean exists = Files.exists(filePath);

        //                断点续传的偏移量
        long continueTransportOffset = 0;

        if (exists) {

            if (metaInfo.isAppendFile()) {
                //  继续断点续传文件
                super.channelRead(ctx, fileReq);
                return;
            }
            continueTransportOffset = Files.size(filePath);
        } else {

            if (metaInfo.isAppendFile()) {
                super.channelRead(ctx, fileReq);
                return;
            }

        }
        // 让client重新发送从断点往后的文件内容
        metaInfo.setContinueTransportOffset(continueTransportOffset);
        metaInfo.setAppendFile(false);
        ctx.writeAndFlush(metaInfo);
        buf.release();
    }
}
